import {defineStore} from 'pinia'
import {CustomLoginService} from '@/api/netshop/customlogin.js'
import useAdminrouter from "@/router/index.js";

export const shopCustomStore = defineStore('custom', {
    state: () => ({
        custom_id: '',
        custom_user_name: '',
        custom_username: '',
        custom_token: ''
    }),
    getters: {},
    actions: {
        async CustomLogin(loginForm) {

            //前台登录录入token
            await CustomLoginService(loginForm)
                .then((response) => {
                        const router = useAdminrouter
                        if (response.data.code === 2000) {
                            this.$patch((state) => {
                                console.log('pinia',response)
                                state.custom_id = response.data.userId
                                state.custom_user_name = response.data.user_name
                                state.custom_username = response.data.username
                                state.custom_token = response.data.token
                                console.log('已经将token存到pinia里面了', state)
                            })
                            localStorage.setItem('custom_id', response.data.userId)
                            localStorage.setItem('custom_user_name', response.data.user_name)
                            localStorage.setItem('custom_token', response.data.token)
                        }
                    }
                ).catch((error) => {
                    console.log('error')
                    router.push({path: '/customlogin'})
                })
        }, // 前台登出，清除token
        async CustomLogout() {
            this.$patch((state) => {
                state.custom_id = ''
                state.custom_user_name = ''
                state.custom_username = ''
                state.custom_token = ''
            })
            localStorage.removeItem('custom_id')
            localStorage.removeItem('custom_user_name')
            localStorage.removeItem('custom_token')
            localStorage.removeItem('custom')
        },
    },
    persist:true
})